package cn.mastor.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedHashMap;

public class StopMixStream {

    // 发送post请求
    public static String sendPost(String url, String param) {
        String result = "";
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            try (
                    PrintWriter out = new PrintWriter(conn.getOutputStream())
            ){
                out.print(param);
                out.flush();
            }
            try (
                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))
            ){
                String line;
                while ((line = in.readLine()) != null) {
                    result += "\n" + line;
                }
            }
        } catch (Exception e) {
            System.out.println(e);
            e.printStackTrace();
        }
        return result;
    }


    public static void main(String args[]) throws UnsupportedEncodingException{

        // zego分配的appid
        Long appid = 123456789L;
        // 发起混流的id_name
        String id_name = "xxx";
        // 混流的roomid
        String live_channel = "xxxx";
        // 混流输出的流id
        String outputStreamId = "os";
        // 混流输出的cdn地址
        String cdnURL = "rtmp://127.0.0.1/xxx/";
        // 时间戳
        String timestamp = Long.toString(System.currentTimeMillis()/1000);
        // 请求结束混流的url,注意正式环境与测试环境的区别, url中包含的access_token参考 "获取Access Token"
        String stopMixStream_url = "https://testwebapi.zego.im/cgi/stop-mix?access_token=";


        LinkedHashMap<String,Object> postJsonData = new LinkedHashMap<>();
        postJsonData.put("id_name", id_name);
        postJsonData.put("live_channel", live_channel);
        postJsonData.put("appid", appid);
        postJsonData.put("stream_id", outputStreamId);
        postJsonData.put("mixurl", cdnURL+outputStreamId);

        String post_json_str = JSONObject.toJSONString(postJsonData);
        System.out.println(post_json_str);
        String access_token = GetToken.getToken("2111975251", "009357ca836fa6109a88c6d9f0398262", "https://testwebapi.zego.im/cgi/token");
        // 发送请求结束混流, access_token 参考 "获取Access Token" 部分
        String ret = StopMixStream.sendPost(stopMixStream_url + access_token, post_json_str);
        System.out.println(ret);

    }
}